import { Device } from "./device.js"
import { DataLine } from "./dataLine.js"
import { Plane } from "./plane.js"
import { SETTINGS, WORDS } from './WORDS.js';

export default class Platform {

    public get index(): number {
        return this._index
    }

    public set index(v: number) {
        if (v !== this._index) {
            this._index = v;
            this.updateOffY(this._index, this._offY)
        }
    }

    _index: number
    _offY: number
    name: string
    plane: Plane
    devices: Map<string, Device>
    dataLines: Map<string, DataLine>
    constructor(index: number, plane: Plane, name = '', offY = -200) {
        name === '' ? (this.name = `PLATFORM_${Date.now()}`) : (this.name = name)
        this._index = index
        this.plane = plane
        this.dataLines = new Map<string, DataLine>()
        this.devices = new Map<string, Device>()
        this._offY = offY
    }

    // getDataLine(id: string) {
    //     return this.dataLines.get(id)
    // }

    // getDevice(id: string) {
    //     return this.devices.get(id)
    // }

    addDataLine(line: DataLine) {
        line.platformIndex = this._index
        // 在实体模型对象里保留：生成的ID & 类型
        this.dataLines.set(line.id, line)
    }

    addDevice(device: Device) {
        device.platformIndex = this._index
        // 在实体模型对象里保留：生成的ID & 类型
        this.devices.set(device.id, device)
    }

    removeModel(model: DataLine | Device) {
        this.removeByIdType(model.id, model.type)
    }

    removeByIdType(id: string, type: string) {
        switch (type) {
            case WORDS.OBJNAME.MODEL_DEVICE:
                this.devices.delete(id)
                break;
            case WORDS.OBJNAME.MODEL_DATALINE:
                this.dataLines.delete(id)
                break;
            default:
                break;
        }
    }

    removeDataLine(id: string) {
        this.dataLines.delete(id)
    }
    removeDevice(id: string) {
        this.devices.delete(id)
    }

    updateOffY(index: number, offY: number) {
        const offYs = index * offY
        this.dataLines.forEach(i => {
            i.obj.position.y = offYs + SETTINGS.DATALINE.OFFSET_Y
        })
        this.devices.forEach(i => {
            i.obj.position.y = offYs + SETTINGS.DEVICE.OFFSET_Y
        })
        this.plane.obj.position.y = offYs + SETTINGS.PLANE.OFFSET_Y
    }

    setIndex(index: number) {
        this.index = index
    }

    toJSON() {
        return {
            index: this._index,
            plane: this.plane.id,
            devices: Array.from(this.devices.values()).map(i => i.toJSON()),
            dataLines: Array.from(this.dataLines.values()).map(i => i.toJSON()),
        }
    }
}